/*
 * Module name : DiscountForm
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

import InputWidget from 'widgets/InputWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';

import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';

const template = require('./templates/DiscountForm.mustache');

const DiscountForm = Mn.View.extend({
    // Send the whole model on submit
    partial: false,
    behaviors: [ModalFormBehavior],
    template: template,
    regions: {
        'order': '.field-order',
        'type_': '.field-type_',
        'description': '.field-description',
        'amount': '.field-amount',
        'percentage': '.field-percentage',
        'tva_id': '.field-tva_id',
    },
    ui: {},
    // Listen to the current's view events
    events: {},
    // Listen to child view events
    childViewEvents: {
        'finish': 'onDatasFinished',
    },
    // Bubble up child view events
    childViewTriggers: {},
    initialize() {
        const config = Radio.channel('config');
        const facade = Radio.channel('facade');
        this.app = Radio.channel('priceStudyApp');

        const tva_options = config.request('get:options', 'tvas');
        const price_study_model = facade.request('get:model', 'price_study');
        const tva_parts = Object.keys(price_study_model.get('tva_parts')).map(x => parseInt(x));
        this.tva_options = tva_options.filter(tva => tva_parts.indexOf(tva.id) != -1);
    },
    onRender() {
        this.refreshFormFields();
    },
    refreshFormFields() {
        this.emptyRegions();
        this.showTypeField();
        this.showOrderField();
        this.showDescriptionField();
        if (this.model.get('type_') == 'percentage') {
            this.showPercentageField();
        } else {
            this.showAmountField();
            this.showTvaField();
        }
    },
    getCommonFieldOptions(label, key, description) {
        let result = {
            field_name: key,
            label: label,
            description: description || '',
            value: this.model.get(key)
        };
        return result;

    },
    showOrderField() {
        let options = this.getCommonFieldOptions('', 'order');
        options['type'] = 'hidden';
        const view = new InputWidget(options);
        this.showChildView('order', view);
    },
    showTypeField() {
        let options = this.getCommonFieldOptions('Type de remise', 'type_');
        options['options'] = [{
                'id': 'amount',
                'label': 'Montant fixe'
            },
            {
                'id': 'percentage',
                'label': 'Pourcentage (valeur calculée)'
            }
        ]
        options['id_key'] = 'id';

        const view = new SelectWidget(options);
        this.showChildView('type_', view);
    },
    showDescriptionField() {
        let options = this.getCommonFieldOptions(
            'Description', 'description', 'Visible dans le document final'
        );
        options['tinymce'] = true;
        options['cid'] = this.model.cid;
        const view = new TextAreaWidget(options);
        this.showChildView('description', view);
    },
    showPercentageField() {
        let options = this.getCommonFieldOptions(
            'Pourcentage', 'percentage',
            'Le montant HT et les taux de TVA seront calculés dynamiquement depuis les valeurs des prestations'
        );
        const view = new InputWidget(options);
        this.showChildView('percentage', view);
    },
    showAmountField() {
        let options = this.getCommonFieldOptions('Montant', 'amount');
        const view = new InputWidget(options);
        this.showChildView('amount', view);
    },
    showTvaField() {
        let options = this.getCommonFieldOptions('TVA', 'tva_id');
        options['options'] = this.tva_options;
        options['id_key'] = 'id';
        options['label_key'] = 'name';

        const view = new SelectWidget(options);
        this.showChildView('tva_id', view);

    },
    templateContext() {
        let title;

        if (this.getOption('edit')) {
            title = "Modifier cette remise";
        } else {
            title = "Ajouter une remise";
        }
        return {
            title: title
        };
    },
    onDatasFinished(key, value) {
        if (key == 'type_') {
            this.model.set(key, value);
            this.refreshFormFields();
        }
    },
    onDestroyModal() {
        this.app.trigger('navigate', 'index');
    },

    onSuccessSync() {
        this.app.trigger('product:changed', this.model);
    }
});
export default DiscountForm